<template>
  <div class="dashboard-container">
    <!-- 第一行（患者信息+统计数据） -->
    <div class="dashboard-row">
      <!-- 患者信息卡片 -->
      <el-card class="dashboard-card patient-card">
        <div slot="header" class="card-header">
          <span>患者基本信息</span>
        </div>
        <div class="patient-info">
          <div class="info-item">
            <span class="info-label">姓名：</span>
            <span class="info-value">{{ patientData.pName || "-" }}</span>
          </div>
          <div class="info-item">
            <span class="info-label">账号：</span>
            <span class="info-value">{{ patientData.pId || "-" }}</span>
          </div>
          <div class="info-item">
            <span class="info-label">性别：</span>
            <span class="info-value">{{ patientData.pGender || "-" }}</span>
          </div>
          <div class="info-item">
            <span class="info-label">年龄：</span>
            <span class="info-value">{{ patientData.pAge || "-" }}</span>
          </div>
          <div class="info-item">
            <span class="info-label">手机号：</span>
            <span class="info-value">{{ patientData.pPhone || "-" }}</span>
          </div>
          <div class="info-item">
            <span class="info-label">出生日期：</span>
            <span class="info-value">{{ patientData.pBirthday || "-" }}</span>
          </div>
          <div class="info-item">
            <span class="info-label">邮箱：</span>
            <span class="info-value">{{ patientData.pEmail || "-" }}</span>
          </div>
        </div>
      </el-card>

      <!-- 统计数据卡片 -->
      <el-card class="dashboard-card stats-card">
        <div slot="header" class="card-header">
          <span>今日数据统计</span>
        </div>
        <div class="stats-content">
          <div class="stat-item">
            <div class="stat-value">{{ todayOrderCount }}</div>
            <div class="stat-label">今日预约挂号</div>
          </div>
          <div class="stat-item">
            <div class="stat-value">{{ todayBedCount }}</div>
            <div class="stat-label">今日住院人数</div>
          </div>
        </div>
      </el-card>
    </div>

    <!-- 第二行（图表） -->
    <div class="dashboard-row">
      <!-- 药物使用情况图表 -->
      <el-card class="dashboard-card chart-card">
        <div slot="header" class="card-header">
          <span>近期用药情况</span>
        </div>
        <div class="chart-container" ref="medicationChart"></div>
      </el-card>

      <!-- 检查项目图表 -->
      <el-card class="dashboard-card chart-card">
        <div slot="header" class="card-header">
          <span>检查项目统计</span>
        </div>
        <div class="chart-container" ref="examinationChart"></div>
      </el-card>
    </div>
  </div>
</template>

<script>
import jwtDecode from "jwt-decode";
import { getToken } from "@/utils/storage.js";
import request from "@/utils/request.js";
import * as echarts from "echarts";
import "echarts-wordcloud";

export default {
  name: "PatientDashboard",
  data() {
    return {
      patientData: {},
      userId: "",
      todayOrderCount: 0,
      todayBedCount: 0,
      charts: {
        medication: null,
        examination: null,
      },
      orderData: [],
    };
  },
  methods: {
    requestPatient() {
      request
        .get("doctor/findPatientById", {
          params: {
            pId: this.userId,
          },
        })
        .then((res) => {
          if (res.data.status != 200)
            return this.$message.error("获取患者数据失败");
          this.patientData = res.data.data;
        });
    },

    fetchPatientOrders() {
      request
        .get("patient/findOrderByPid", {
          params: {
            pId: this.userId,
          },
        })
        .then((res) => {
          if (res.data.status === 200) {
            this.orderData = res.data.data;
            this.$nextTick(() => {
              this.initMedicationChart();
              this.initExaminationChart();
            });
          }
        });
    },

    loadTodayData() {
      request.get("order/orderPeople").then((res) => {
        if (res.data.status === 200) {
          this.todayOrderCount = res.data.data;
        }
      });

      request.get("bed/bedPeople").then((res) => {
        if (res.data.status === 200) {
          this.todayBedCount = res.data.data;
        }
      });
    },

    initCharts() {
      if (this.charts.medication) this.charts.medication.dispose();
      if (this.charts.examination) this.charts.examination.dispose();
      
      this.charts.medication = echarts.init(this.$refs.medicationChart);
      this.charts.examination = echarts.init(this.$refs.examinationChart);
      
      this.fetchPatientOrders();
    },

    parseMedicationData() {
      const medications = {};

      this.orderData.forEach((order) => {
        if (order.oDrug && order.oDrug.trim() !== "药物总价0元") {
          const drugPart = order.oDrug.split("药物总价")[0].trim();
          if (drugPart) {
            const drugItems = drugPart.split(/\s+/).filter((item) => item.includes('*'));
            
            drugItems.forEach((item) => {
              try {
                const [name, pricePart, quantityPart] = item.split('*');
                const price = parseInt(pricePart);
                const quantity = parseInt(quantityPart) || 1;

                if (!medications[name]) {
                  medications[name] = {
                    count: 0,
                    price: price,
                  };
                }
                medications[name].count += quantity;
              } catch (e) {
                console.warn("解析药物数据出错:", item);
              }
            });
          }
        }
      });

      return Object.keys(medications).map((name) => ({
        name,
        value: medications[name].count,
        price: medications[name].price,
      }));
    },

    parseExaminationData() {
      const examinations = {};

      this.orderData.forEach((order) => {
        if (order.oCheck && order.oCheck.trim() !== "项目总价0元") {
          const checkPart = order.oCheck.split("项目总价")[0].trim();
          if (checkPart) {
            const checkItems = checkPart.split(/\s+/).filter((item) => item.includes('*'));
            
            checkItems.forEach((item) => {
              try {
                const checkName = item.split('*')[0];
                examinations[checkName] = (examinations[checkName] || 0) + 1;
              } catch (e) {
                console.warn("解析检查项目出错:", item);
              }
            });
          }
        }
      });

      return Object.keys(examinations).map((name) => ({
        name,
        value: examinations[name],
      }));
    },

    initMedicationChart() {
      const medicationData = this.parseMedicationData();

      if (medicationData.length === 0) {
        medicationData.push({
          name: "暂无用药数据",
          value: 1,
          price: 0,
        });
      }

      const option = {
        tooltip: {
          formatter: params => {
            return `
              <div style="font-weight:bold">${params.name}</div>
              使用次数: ${params.value}次<br/>
              单价: ${params.data.price}元
            `;
          }
        },
        series: [{
          type: 'wordCloud',
          shape: 'circle',
          left: 'center',
          top: 'center',
          width: '90%',
          height: '90%',
          right: null,
          bottom: null,
          sizeRange: [12, 40],
          rotationRange: [0, 0],
          rotationStep: 45,
          gridSize: 8,
          drawOutOfBound: false,
          textStyle: {
            fontFamily: 'sans-serif',
            fontWeight: 'bold',
            color: () => {
              return this.getDrugColor();
            }
          },
          emphasis: {
            textStyle: {
              shadowBlur: 10,
              shadowColor: '#333'
            }
          },
          data: medicationData
        }]
      };

      this.charts.medication.setOption(option);
    },

    initExaminationChart() {
      const examinationData = this.parseExaminationData();

      if (examinationData.length === 0) {
        examinationData.push({
          name: "暂无检查数据",
          value: 1,
        });
      }

      const option = {
        tooltip: {
          trigger: "axis",
          axisPointer: {
            type: "shadow",
          },
          formatter: "{b}: {c}次",
        },
        grid: {
          left: "3%",
          right: "4%",
          bottom: "3%",
          containLabel: true,
        },
        xAxis: {
          type: "value",
          axisLabel: {
            formatter: (value) => (value % 1 === 0 ? value : ""),
          },
          interval: 1,
        },
        yAxis: {
          type: "category",
          data: examinationData.map((item) => item.name),
        },
        series: [{
          name: "检查次数",
          type: "bar",
          data: examinationData.map((item) => item.value),
          itemStyle: {
            color: (params) => this.getDrugColor(),
          },
          label: {
            show: true,
            position: "right",
            formatter: "{c}次",
          },
        }],
      };

      this.charts.examination.setOption(option);
    },

    getDrugColor() {
      const colors = [
        "#5470C6", "#91CC75", "#FAC858", "#EE6666", 
        "#73C0DE", "#3BA272", "#FC8452", "#9A60B4"
      ];
      return colors[Math.floor(Math.random() * colors.length)];
    },

    tokenDecode(token) {
      if (token !== null) return jwtDecode(token);
    },

    resizeCharts() {
      Object.values(this.charts).forEach((chart) => {
        if (chart) chart.resize();
      });
    },
  },
  mounted() {
    this.initCharts();
    window.addEventListener("resize", this.resizeCharts);
  },
  created() {
    this.userId = this.tokenDecode(getToken()).pId;
    this.requestPatient();
    this.loadTodayData();
  },
  beforeDestroy() {
    window.removeEventListener("resize", this.resizeCharts);
    Object.values(this.charts).forEach((chart) => {
      if (chart) chart.dispose();
    });
  },
};
</script>

<style scoped>
.dashboard-container {
  width: 100%;
  height: 100%;
  display: flex;
  flex-direction: column;
  padding: 0;
  box-sizing: border-box;
}

.dashboard-row {
  display: flex;
  flex: 1;
  min-height: 0;
  margin-bottom: 16px;
}

.dashboard-row:last-child {
  margin-bottom: 0;
}

.dashboard-card {
  flex: 1;
  margin-right: 16px;
  display: flex;
  flex-direction: column;
  min-height: 0;
}

.dashboard-card:last-child {
  margin-right: 0;
}

.card-header {
  font-size: 16px;
  font-weight: bold;
  color: #303133;
}

.patient-card {
  min-width: 300px;
}

.patient-info {
  flex: 1;
  display: flex;
  flex-direction: column;
  padding: 10px;
  overflow: auto;
}

.info-item {
  display: flex;
  margin-bottom: 12px;
  font-size: 14px;
}

.info-label {
  color: #909399;
  min-width: 80px;
  text-align: right;
  margin-right: 10px;
}

.info-value {
  color: #606266;
  flex: 1;
}

.stats-content {
  flex: 1;
  display: flex;
  justify-content: space-around;
  align-items: center;
  padding: 10px;
}

.stat-item {
  text-align: center;
}

.stat-value {
  font-size: 24px;
  font-weight: bold;
  color: #409eff;
  margin-bottom: 8px;
}

.stat-label {
  font-size: 14px;
  color: #909399;
}

.chart-card {
  min-width: 300px;
}

.chart-container {
  width: 100%;
  height: 100%;
  min-height: 200px;
}

@media (max-width: 992px) {
  .dashboard-row {
    flex-direction: column;
    margin-bottom: 0;
  }

  .dashboard-card {
    margin-right: 0;
    margin-bottom: 16px;
    min-height: auto;
  }

  .dashboard-card:last-child {
    margin-bottom: 0;
  }

  .patient-info {
    flex-direction: row;
    flex-wrap: wrap;
  }

  .info-item {
    width: 50%;
    margin-bottom: 8px;
  }

  .stats-content {
    flex-direction: column;
  }

  .stat-item {
    margin-bottom: 16px;
  }
}
</style>